package com.xnx3.kefu.superadmin.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.ConsoleUtil;
import com.xnx3.BaseVO;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.kefu.core.bean.ChatUserBean;
import com.xnx3.kefu.core.socket.NettyHandler;
import com.xnx3.kefu.core.util.SocketUtil;
import com.xnx3.kefu.core.util.UserUtil;
import com.xnx3.kefu.superadmin.vo.OnlineUserVO;
import com.xnx3.kefu.superadmin.vo.bean.OnlineUserBean;
import io.netty.channel.Channel;

/**
 * 用户管理
 * @author 管雷鸣
 */
@Controller(value="KefuSuperadminUserController")
@RequestMapping("/kefu/superadmin/")
public class UserController extends BaseController {
	@Resource
	private UserService userService;
	@Resource
	private SqlService sqlService;
	@Resource
	private SqlCacheService sqlCacheService;
	
	/**
	 * 获取当前在线用户列表
	 */
	@ResponseBody
	@RequestMapping(value="onlineUser${api.suffix}")	//, method = RequestMethod.POST
	public OnlineUserVO onlineUser(HttpServletRequest request){
		if(!haveSuperAdminAuth()){
			OnlineUserVO vo = new OnlineUserVO();
			vo.setBaseVO(BaseVO.FAILURE, "无权使用");
			return vo;
		}
		
		OnlineUserVO vo = new OnlineUserVO();
		ActionLogUtil.insert(request, "查看当前在线用户列表");
		
//		JSONArray jsonArray = new JSONArray();
		List<OnlineUserBean> onlineUserList = new ArrayList<OnlineUserBean>();
		for(Map.Entry<String, List<Channel>> entry : SocketUtil.channelMap.entrySet()){
//			JSONObject itemJson = new JSONObject(); 
			
			OnlineUserBean bean = new OnlineUserBean();
			ChatUserBean chatUser = UserUtil.getUser(entry.getKey());
			if(chatUser == null){
				ConsoleUtil.error("user不应该为null， channelId:"+entry.getKey());
				continue;
			}
//			itemJson.put("user", user);
			bean.setUser(chatUser);
			
			List<String> list = new ArrayList<String>();
			for (int i = 0; i < entry.getValue().size(); i++) {
				Channel channel = entry.getValue().get(i);
				list.add(channel.id().asShortText());
			}
			bean.setChannelIdList(list);
//			itemJson.put("channelId", list);
			//jsonArray.add(itemJson);
			onlineUserList.add(bean);
		}
		
//		JSONObject json = new JSONObject();
//		json.put("result", "1");
		vo.setOnlineUserNumber(onlineUserList.size());
		vo.setCurrentChannelNumber(NettyHandler.channelGroup.size());
		vo.setOnlineUserList(onlineUserList);
//		json.put("onlineUserNumber", jsonArray.size());
		
		return vo;
	}
	

}
